package com.woniuxy.system.interceptor;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.woniuxy.system.util.TokenUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${jwt.signature}")
    private String signature;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        //判断是否为NULL
        if(!StringUtils.hasLength(authorization)){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());//401
            return false;
        }
        // 前端： config.headers.Authorization = "Bearer " + token;  所以这里要去除前缀
        authorization = authorization.replace("Bearer ", "");
        //校验令牌是否合法
        if(!JWTUtil.verify(authorization,signature.getBytes())){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());//401
            return false;
        }
        //解析IP地址 & 发送HTTP请求的服务器IP地址进行比对
        JWT jwt = JWTUtil.parseToken(authorization);
        String requestIP = (String)jwt.getPayload("requestIp");//令牌内部的IP地址

        // 获取当前来访者的ip
        String httpIP = TokenUtils.getRequestIP(request);
        // 判断：token中的ip与来访者的ip不一致，返回401状态码 （登录是在一台服务器，访问资源是另外一台服务器，说明token泄露。）
        if(!requestIP.equals(httpIP)){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());//401
            return false;
        }

        // 判断令牌的过期时间是否超过当前时间，如果超过：令牌过期
        String exp = (String)jwt.getPayload("exp");
        LocalDateTime expTime = LocalDateTime.parse(exp, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        if(expTime.isBefore(LocalDateTime.now())){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());//401
            return false;
        }
        //一切正常，则正常放行HTTP请求
        return true;
    }
}